/**
 * 销售出库单 - 新建或编辑界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Sale.WSEditForm", {
  extend: "PSI.AFX.Form.EditForm",
  config: {
    genBill: false,
    sobillRef: null,
    soKeyMap: null, // 从销售订单创建销售出库单的时候，传入该KeyMap
  },

  mixins: ["PSI.Mix.GoodsPrice"],

  /**
   * @override
   */
  initComponent() {
    const me = this;

    me._readonly = false;
    const entity = me.getEntity();
    me.adding = entity == null;

    const action = entity == null ? "新建" : "编辑";
    const title = me.formatTitleLabel("销售出库单", action);

    PCL.apply(me, {
      header: false,
      padding: "0 0 0 0",
      border: 0,
      maximized: true,
      layout: "border",
      tbar: [{
        id: me.buildId(me, "dfTitle"),
        value: title, xtype: "displayfield"
      }, "->", {
        text: "保存 <span class='PSI-shortcut-DS'>Alt + S</span>",
        tooltip: "快捷键：Alt + S",
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-button-ok",
        handler: me._onOK,
        scope: me,
        id: me.buildId(me, "buttonSave")
      }, "-", {
        text: "取消",
        iconCls: "PSI-tb-close",
        ...PSI.Const.BTN_STYLE,
        handler() {
          if (me._readonly) {
            me.close();
            return;
          }

          me.confirm("请确认是否取消当前操作？", () => {
            me.close();
          });
        },
        scope: me,
        id: me.buildId(me, "buttonCancel")
      }, "-", {
        id: me.buildId(me, "displayFieldBarcode"),
        value: "条码录入",
        xtype: "displayfield"
      }, {
        xtype: "textfield",
        cls: "PSI-toolbox-barcode",
        id: me.buildId(me, "editBarcode"),
        listeners: {
          specialkey: {
            fn: me._onEditBarcodeKeydown,
            scope: me
          }
        }
      }, " ", "-", {
        text: "表单通用操作指南",
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-help",
        handler() {
          me.focus();
          window.open(me.URL("Home/Help/index?t=commBill"));
        }
      }, "-", {
        margin: "5 5 5 0",
        cls: "PSI-toolbox",
        labelWidth: 0,
        width: 90,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield"
      }],
      items: [{
        region: "center",
        border: 0,
        bodyPadding: 10,
        layout: "fit",
        items: [me.getGoodsGrid()]
      }, {
        region: "north",
        border: 0,
        layout: {
          type: "table",
          columns: 4,
          tableAttrs: PSI.Const.TABLE_LAYOUT_SMALL,
        },
        height: 105,
        bodyPadding: 10,
        items: [{
          xtype: "hidden",
          id: me.buildId(me, "hiddenId"),
          name: "id",
          value: entity == null ? null : entity.get("id")
        }, {
          id: me.buildId(me, "editRef"),
          fieldLabel: "单号",
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          width: 175,
          xtype: "displayfield",
          value: me.toFieldNoteText("保存后自动生成")
        }, {
          id: me.buildId(me, "editBizDT"),
          fieldLabel: "业务日期",
          allowBlank: false,
          blankText: "没有输入业务日期",
          labelAlign: "right",
          labelSeparator: "",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "datefield",
          format: "Y-m-d",
          value: new Date(),
          name: "bizDT",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editBizUser"),
          fieldLabel: "业务员",
          xtype: "psi_userfield",
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          allowBlank: false,
          blankText: "没有输入业务员",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editWarehouse"),
          fieldLabel: "出库仓库",
          labelWidth: 65,
          labelAlign: "right",
          labelSeparator: "",
          xtype: "psi_warehousefield",
          fid: "2002",
          allowBlank: false,
          blankText: "没有输入出库仓库",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          width: 430,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
        }, {
          id: me.buildId(me, "editCustomer"),
          xtype: "psi_customerfield",
          fieldLabel: "客户",
          showAddButton: true,
          allowBlank: false,
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          colspan: 2,
          width: 430,
          blankText: "没有输入客户",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
          callbackFunc: me._setCustomerExtData,
          callbackFuncScope: me,
        }, {
          id: me.buildId(me, "editReceivingType"),
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "收款方式",
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [["0", "记应收账款"],
            ["1", "现金收款"],
            ["2", "用预收款支付"]]
          }),
          value: "0",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editDealAddress"),
          labelWidth: 65,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "送货地址",
          xtype: "textfield",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
          width: 430
        }, {
          id: me.buildId(me, "editBillMemo"),
          labelWidth: 60,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "备注",
          xtype: "textfield",
          listeners: {
            specialkey: {
              fn: me._onEditBillMemoSpecialKey,
              scope: me
            }
          },
          colspan: 3,
          width: 645
        }]
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.hiddenId = PCL.getCmp(me.buildId(me, "hiddenId"));
    me.editRef = PCL.getCmp(me.buildId(me, "editRef"));
    me.editBizDT = PCL.getCmp(me.buildId(me, "editBizDT"));
    me.editBizUser = PCL.getCmp(me.buildId(me, "editBizUser"));
    me.editWarehouse = PCL.getCmp(me.buildId(me, "editWarehouse"));
    me.editCustomer = PCL.getCmp(me.buildId(me, "editCustomer"));
    me.editReceivingType = PCL.getCmp(me.buildId(me, "editReceivingType"));
    me.editDealAddress = PCL.getCmp(me.buildId(me, "editDealAddress"));
    me.editBillMemo = PCL.getCmp(me.buildId(me, "editBillMemo"));

    // AFX
    me.__editorList = [
      me.editBizDT, me.editBizUser, me.editWarehouse,
      me.editCustomer, me.editReceivingType, me.editDealAddress,
      me.editBillMemo];

    me.columnActionDelete = PCL.getCmp(me.buildId(me, "columnActionDelete"));
    me.columnActionAdd = PCL.getCmp(me.buildId(me, "columnActionAdd"));
    me.columnActionAppend = PCL.getCmp(me.buildId(me, "columnActionAppend"));

    me.displayFieldBarcode = PCL.getCmp(me.buildId(me, "displayFieldBarcode"));
    me.editBarcode = PCL.getCmp(me.buildId(me, "editBarcode"));
    me.buttonSave = PCL.getCmp(me.buildId(me, "buttonSave"));
    me.buttonCancel = PCL.getCmp(me.buildId(me, "buttonCancel"));

    me.dfTitle = PCL.getCmp(me.buildId(me, "dfTitle"));

    me._keyMap = PCL.create("PCL.util.KeyMap", PCL.getBody(), {
      key: "S",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        if (me._readonly) {
          return;
        }

        // 切换焦点，主要是用于触发Grid的编辑事件
        me.focus();

        me._onOK.apply(me, []);
      },
      scope: me
    });
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this

    const km = me.getSoKeyMap();
    if (km) {
      km.enable();
    }

    PCL.WindowManager.hideAll();

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    me._keyMap.destroy();

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    const km = me.getSoKeyMap();
    if (km) {
      km.disable();
    }

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    me.editWarehouse.focus();

    // TODO 这个变量似乎没有使用，需要进一步Review代码来确认
    me._canEditGoodsPrice = false;

    const el = me.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Sale/wsBillInfo"),
      params: {
        id: me.hiddenId.getValue(),
        sobillRef: me.getSobillRef()
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);

          if (data.canEditGoodsPrice) {
            me._canEditGoodsPrice = true;
            me.columnGoodsPrice.setEditor({
              xtype: "numberfield",
              allowDecimals: true,
              hideTrigger: true
            });
            me.columnGoodsMoney.setEditor({
              xtype: "numberfield",
              allowDecimals: true,
              hideTrigger: true
            });
          }

          if (me.getGenBill()) {
            // 从销售订单生成销售出库单
            me.editCustomer.setIdValue(data.customerId);
            me.editCustomer.setValue(data.customerName);
            me.editBizUser.setIdValue(data.bizUserId);
            me.editBizUser.setValue(data.bizUserName);
            me.editBizDT.setValue(data.dealDate);
            me.editReceivingType.setValue(data.receivingType);
            me.editBillMemo.setValue(data.memo);

            me.editDealAddress.setValue(data.dealAddress);

            const store = me.getGoodsGrid().getStore();
            store.removeAll();
            store.add(data.items);

            me.editCustomer.setReadOnly(true);
            me.columnActionDelete.hide();
            me.columnActionAdd.hide();
            me.columnActionAppend.hide();

            me.editBarcode.setDisabled(true);

            if (data.warehouseId) {
              me.editWarehouse.setIdValue(data.warehouseId);
              me.editWarehouse.setValue(data.warehouseName);
            }
          } else {

            if (data.ref) {
              me.editRef.setValue(me.toFieldNoteText(data.ref));
            }

            me.editCustomer.setIdValue(data.customerId);
            me.editCustomer.setValue(data.customerName);
            me.editCustomer.setShowAddButton(data.showAddCustomerButton);

            me.editWarehouse.setIdValue(data.warehouseId);
            me.editWarehouse.setValue(data.warehouseName);

            me.editBizUser.setIdValue(data.bizUserId);
            me.editBizUser.setValue(data.bizUserName);
            if (data.bizDT) {
              me.editBizDT.setValue(data.bizDT);
            }
            if (data.receivingType) {
              me.editReceivingType.setValue(data.receivingType);
            }
            if (data.memo) {
              me.editBillMemo.setValue(data.memo);
            }
            me.editDealAddress.setValue(data.dealAddress);

            const store = me.getGoodsGrid().getStore();
            store.removeAll();
            if (data.items) {
              store.add(data.items);
            }
            if (store.getCount() == 0) {
              store.add({});
            }

            if (data.billStatus && data.billStatus != 0) {
              me.setBillReadonly();
            }
          }
        } else {
          me.showInfo("网络错误")
        }
      }
    });
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    PCL.getBody().mask("正在保存中...");
    me.ajax({
      url: me.URL("SLN0001/Sale/editWSBill"),
      params: {
        adding: me.adding ? "1" : "0",
        jsonStr: me.getSaveData(),
        checkInv: 1
      },
      callback(options, success, response) {
        PCL.getBody().unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            me.close();
            const pf = me.getParentForm();
            if (pf) {
              pf.refreshMainGrid.apply(pf, [data.id]);
            }
            me.tip("成功保存数据", true);
          } else {
            if (data.checkInv == "1") {
              // 检查到库存不足，提醒用户
              me.confirm(data.msg, () => {
                me.ajax({
                  url: me.URL("SLN0001/Sale/editWSBill"),
                  params: {
                    jsonStr: me.getSaveData(),
                    checkInv: 0
                  },
                  callback(options, success, response) {
                    PCL.getBody().unmask();

                    if (success) {
                      me.close();
                      const pf = me.getParentForm();
                      if (pf) {
                        pf.refreshMainGrid.apply(pf, [data.id]);
                      }
                      me.tip("成功保存数据", true);
                    } else {
                      me.showInfo(data.msg);
                    }
                  }
                });
              })
            } else {
              me.showInfo(data.msg);
            }
          }
        }
      }
    });
  },

  /**
   * @private
   */
  _onEditBillMemoSpecialKey(field, e) {
    const me = this;

    if (me._readonly) {
      return;
    }

    if (e.getKey() == e.ENTER) {
      const store = me.getGoodsGrid().getStore();
      if (store.getCount() == 0) {
        store.add({});
      }
      me.getGoodsGrid().focus();
      me._cellEditing.startEdit(0, 1);
    }
  },

  /**
   * @private
   */
  getGoodsGrid() {
    const me = this;

    if (me._goodsGrid) {
      return me._goodsGrid;
    }

    const modelName = me.buildModelName(me, "WSBillDetail_EditForm");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "goodsId", "goodsCode", "goodsName",
        "goodsSpec", "unitName", "goodsCount", {
          name: "goodsMoney",
          type: "float"
        }, "goodsPrice", "sn", "memo", "soBillDetailId", {
          name: "taxRate",
          type: "int"
        }, {
          name: "tax",
          type: "float"
        }, {
          name: "moneyWithTax",
          type: "float"
        }, "goodsPriceWithTax"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._cellEditing = PCL.create("PSI.UX.CellEditing", {
      clicksToEdit: 1,
      listeners: {
        edit: {
          fn: me._onCellEditingAfterEdit,
          scope: me
        }
      }
    });

    me._goodsGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-EF",
      viewConfig: {
        enableTextSelection: true,
        markDirty: !me.adding
      },
      features: [{
        ftype: "summary"
      }],
      plugins: [me._cellEditing],
      columnLines: true,
      columns: [PCL.create("PCL.grid.RowNumberer", {
        text: "#",
        width: 30
      }), {
        header: "商品编码",
        dataIndex: "goodsCode",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        editor: {
          xtype: "psi_goods_with_saleprice_field",
          parentCmp: me,
          editCustomerName: me.buildId(me, "editCustomer"),
          editWarehouseName: me.buildId(me, "editWarehouse"),
          goodsInfoCallbackFunc: me._setGoodsInfo,
          goodsInfoCallbackFuncScope: me,
        }
      }, {
        menuDisabled: true,
        draggable: false,
        sortable: false,
        header: "品名/规格型号",
        dataIndex: "goodsName",
        width: 330,
        renderer(value, metaData, record) {
          return record.get("goodsName") + " " + record.get("goodsSpec");
        }
      }, {
        header: "销售数量",
        dataIndex: "goodsCount",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        width: 90,
        editor: {
          xtype: "numberfield",
          allowDecimals: PSI.Const.GC_DEC_NUMBER > 0,
          decimalPrecision: PSI.Const.GC_DEC_NUMBER,
          minValue: 0,
          hideTrigger: true
        }
      }, {
        header: "单位",
        dataIndex: "unitName",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        width: 60,
        align: "center"
      }, {
        header: "销售单价",
        dataIndex: "goodsPrice",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90,
        id: "columnGoodsPrice",
        summaryRenderer() {
          return "金额合计";
        }
      }, {
        header: "销售金额",
        dataIndex: "goodsMoney",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90,
        id: "columnGoodsMoney",
        summaryType: "sum"
      }, {
        header: "含税价",
        dataIndex: "goodsPriceWithTax",
        menuDisabled: true,
        draggable: false,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90,
        editor: {
          xtype: "numberfield",
          hideTrigger: true
        }
      }, {
        header: "税率(%)",
        dataIndex: "taxRate",
        align: "right",
        format: "0",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        width: 60
      }, {
        header: "税金",
        dataIndex: "tax",
        align: "right",
        xtype: "numbercolumn",
        width: 90,
        menuDisabled: true,
        sortable: false,
        draggable: false,
        editor: {
          xtype: "numberfield",
          hideTrigger: true
        },
        summaryType: "sum"
      }, {
        header: "价税合计",
        dataIndex: "moneyWithTax",
        align: "right",
        xtype: "numbercolumn",
        width: 90,
        menuDisabled: true,
        sortable: false,
        draggable: false,
        editor: {
          xtype: "numberfield",
          hideTrigger: true
        },
        summaryType: "sum"
      }, {
        header: "序列号",
        dataIndex: "sn",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        editor: {
          xtype: "textfield"
        }
      }, {
        header: "备注",
        dataIndex: "memo",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        editor: {
          xtype: "textfield"
        }
      }, {
        header: "",
        align: "center",
        menuDisabled: true,
        draggable: false,
        width: 50,
        xtype: "actioncolumn",
        id: me.buildId(me, "columnActionDelete"),
        items: [{
          icon: me.URL("Public/Images/icons/delete.png"),
          tooltip: "删除当前记录",
          handler(grid, row) {
            const store = grid.getStore();
            store.remove(store.getAt(row));
            if (store.getCount() == 0) {
              store.add({});
            }
          },
          scope: me
        }]
      }, {
        header: "",
        id: me.buildId(me, "columnActionAdd"),
        align: "center",
        menuDisabled: true,
        draggable: false,
        width: 50,
        xtype: "actioncolumn",
        items: [{
          icon: me.URL("Public/Images/icons/insert.png"),
          tooltip: "在当前记录之前插入新记录",
          handler(grid, row) {
            const store = grid.getStore();
            store.insert(row, [{}]);
          },
          scope: me
        }]
      }, {
        header: "",
        id: me.buildId(me, "columnActionAppend"),
        align: "center",
        menuDisabled: true,
        draggable: false,
        width: 50,
        xtype: "actioncolumn",
        items: [{
          icon: me.URL("Public/Images/icons/add.png"),
          tooltip: "在当前记录之后新增记录",
          handler(grid, row) {
            const store = grid.getStore();
            store.insert(row + 1, [{}]);
          },
          scope: me
        }]
      }],
      store,
      listeners: {
        cellclick() {
          return !me._readonly;
        }
      }
    });

    return me._goodsGrid;
  },

  /**
   * @private
   */
  _onCellEditingAfterEdit(editor, e) {
    const me = this;

    const fieldName = e.field;
    const goods = e.record;
    const oldValue = e.originalValue;
    if (fieldName == "goodsCount") {
      if (goods.get(fieldName) != oldValue) {
        me.calcMoney(goods);
      }
    } else if (fieldName == "goodsPrice") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcMoney(goods);
      }
    } else if (fieldName == "goodsMoney") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcPrice(goods);
      }
    } else if (fieldName == "memo") {
      if (me.getGenBill()) {
        // 从销售订单生成入库单的时候不能新增明细记录
        return;
      }

      const store = me.getGoodsGrid().getStore();
      if (e.rowIdx == store.getCount() - 1) {
        store.add({});
        me.getGoodsGrid().getSelectionModel().select(e.rowIdx + 1);
        me._cellEditing.startEdit(e.rowIdx + 1, 1);
      }
    } else if (fieldName == "moneyWithTax") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcTax(goods);
      }
    } else if (fieldName == "tax") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcMoneyWithTax(goods);
      }
    } else if (fieldName == "goodsPriceWithTax") {
      if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
        me.calcMoney2(goods);
      }
    }
  },

  /**
   * @private
   */
  _setGoodsInfo(data) {
    const me = this;
    const item = me.getGoodsGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const goods = item[0];

    goods.set("goodsId", data.id);
    goods.set("goodsCode", data.code);
    goods.set("goodsName", data.name);
    goods.set("unitName", data.unitName);
    goods.set("goodsSpec", data.spec);
    goods.set("goodsPrice", data.salePrice);

    goods.set("taxRate", data.taxRate);

    me.calcMoney(goods);
  },

  /**
   * @private
   */
  getSaveData() {
    const me = this;

    const result = {
      id: me.hiddenId.getValue(),
      bizDT: PCL.Date.format(me.editBizDT.getValue(), "Y-m-d"),
      customerId: me.editCustomer.getIdValue(),
      warehouseId: me.editWarehouse.getIdValue(),
      bizUserId: me.editBizUser.getIdValue(),
      receivingType: me.editReceivingType.getValue(),
      billMemo: me.editBillMemo.getValue(),
      sobillRef: me.getSobillRef(),
      dealAddress: me.editDealAddress.getValue(),
      items: []
    };

    const store = me.getGoodsGrid().getStore();
    for (let i = 0; i < store.getCount(); i++) {
      const item = store.getAt(i);
      result.items.push({
        id: item.get("id"),
        goodsId: item.get("goodsId"),
        goodsCount: item.get("goodsCount"),
        goodsPrice: item.get("goodsPrice"),
        goodsMoney: item.get("goodsMoney"),
        sn: item.get("sn"),
        memo: item.get("memo"),
        soBillDetailId: item.get("soBillDetailId"),
        taxRate: item.get("taxRate"),
        tax: item.get("tax"),
        moneyWithTax: item.get("moneyWithTax"),
        goodsPriceWithTax: item.get("goodsPriceWithTax")
      });
    }

    return me.encodeJSON(result);
  },

  /**
   * @private
   */
  setBillReadonly() {
    const me = this;
    me._readonly = true;
    me.dfTitle.setValue(me.formatTitleLabel("销售出库单", "查看"));

    me.displayFieldBarcode.setDisabled(true);
    me.editBarcode.setDisabled(true);
    me.buttonSave.setDisabled(true);
    me.buttonSave.setText("保存");
    me.buttonSave.setTooltip("");
    me.buttonCancel.setText("关闭");

    me.editBizDT.setReadOnly(true);
    me.editCustomer.setReadOnly(true);
    me.editWarehouse.setReadOnly(true);
    me.editBizUser.setReadOnly(true);
    me.editBillMemo.setReadOnly(true);
    me.editDealAddress.setReadOnly(true);
    me.editReceivingType.setReadOnly(true);

    me.columnActionDelete.hide();
    me.columnActionAdd.hide();
    me.columnActionAppend.hide();
  },

  /**
   * @private
   */
  addGoodsByBarCode(goods) {
    if (!goods) {
      return;
    }

    const me = this;
    const store = me.getGoodsGrid().getStore();

    if (store.getCount() == 1) {
      const r = store.getAt(0);
      const id = r.get("goodsId");
      if (id == null || id == "") {
        store.removeAll();
      }
    }

    store.add(goods);
  },

  /**
   * @private
   */
  _onEditBarcodeKeydown(field, e) {
    if (e.getKey() == e.ENTER) {
      const me = this;

      const el = PCL.getBody();
      el.mask("查询中...");
      me.ajax({
        url: me.URL("SLN0001/Goods/queryGoodsInfoByBarcode"),
        params: {
          barcode: field.getValue()
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              const goods = {
                goodsId: data.id,
                goodsCode: data.code,
                goodsName: data.name,
                goodsSpec: data.spec,
                unitName: data.unitName,
                goodsCount: 1,
                goodsPrice: data.salePrice,
                goodsMoney: data.salePrice,
                taxRate: data.taxRate
              };
              me.addGoodsByBarCode(goods);

              const edit = me.editBarcode;
              edit.setValue(null);
              edit.focus();
            } else {
              const edit = me.editBarcode;
              edit.setValue(null);
              me.showInfo(data.msg, () => {
                edit.focus();
              });
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      });
    }
  },

  /**
   * @private
   */
  _setCustomerExtData(data) {
    const me = this;
    me.editDealAddress.setValue(data.address_receipt);

    if (data.warehouseId) {
      me.editWarehouse.setIdValue(data.warehouseId);
      me.editWarehouse.setValue(data.warehouseName);
    }
  }
});
